#include "SharedObject.h"

namespace MiniWindow
{
	SharedObject::SharedObject()
	{
		this->shared = null;
		this->referenced = null;
		this->AttachReference();
	}
	SharedObject::SharedObject(Data* data)
	{
		this->shared = data;
		this->referenced = null;
		this->AttachReference();
	}
	SharedObject::SharedObject(const SharedObject& o)
	{
		this->shared = o.shared;
		this->referenced = o.referenced;
		this->AttachReference();
	}
	SharedObject::~SharedObject()
	{
		this->DetachReference();
	}
	void SharedObject::AttachReference()
	{
		if (null != this->referenced)
		{
			++(*this->referenced);
		}
		else
		{
			this->referenced = new ushort(1);
		}
	}
	void SharedObject::DetachReference()
	{
		if (null != this->referenced)
		{
			if ((--(*this->referenced)) < 1)
			{
				delete this->shared;
				delete this->referenced;
			}
			this->shared = null;
			this->referenced = null;
		}
	}
	bool SharedObject::IsReferenced() const
	{
		if (null == this->referenced)
		{
			return false;
		}
		return (*this->referenced) > 1;
	}
	bool SharedObject::IsReferenced(const SharedObject& o) const
	{
		if (null == this->referenced || null == o.referenced)
		{
			return false;
		}
		return this->referenced == o.referenced;
	}
	SharedObject& SharedObject::operator=(const SharedObject& o)
	{
		if (this->IsReferenced(o))
		{
			return *this;
		}
		this->DetachReference();
		this->shared = o.shared;
		this->referenced = o.referenced;
		this->AttachReference();
		return *this;
	}
	void SharedObject::SetData(Data* data)
	{
		if (null != this->shared)
		{
			delete this->shared;
		}
		this->shared = data;
	}

	SharedObject::Data::Data()
	{
	}
	SharedObject::Data::~Data()
	{
	}
}